import glob
import json
import os
import shutil
import textwrap
import time

from PIL import Image
from PIL import ImageDraw, ImageFont

from Files.models import File
from Master.models import Master
from User.models import User
from Util import verify_token, back_failed, back_success


def draw(
        content="",
        fontCount=22,
        bg_path="assets/images/default_background.png",
        font_path='assets/font/default.ttf',
        x=160,
        y=90,
        spacing=9.8,
        font_color="black",
        line=30,
        temPath="temp",
        fontSize=48):
    userTempPath = 'assets' + os.sep + 'temp' + os.sep + str(temPath) + os.sep
    if not os.path.exists(userTempPath):
        os.makedirs(userTempPath)
    for f in glob.glob(os.path.join(userTempPath, "*")):
        os.remove(f)  # 删除images,font
    warp = textwrap.wrap(content, width=int(fontCount))
    file_page = 0
    pathArr = []

    for page in range(0, len(warp), line):
        file_path = userTempPath + str(int(time.time())) + "-" + str(file_page) + '.png'
        estimatedMaximum = page + line
        im = Image.open(bg_path)
        drawer = ImageDraw.Draw(im)
        font = ImageFont.truetype(font_path, fontSize)
        start_y = y
        if len(warp) < estimatedMaximum:
            for i in range(page, len(warp)):
                w, h = drawer.textsize(warp[i], font=font)
                drawer.text((x, start_y), warp[i], font=font, fill=font_color)
                start_y += h + spacing
            im.save(file_path, 'PNG')
            im.close()
        else:
            for i in range(page, estimatedMaximum):
                w, h = drawer.textsize(warp[i], font=font)
                drawer.text((x, start_y), warp[i], font=font, fill=font_color)
                start_y += h + spacing
            im.save(file_path, 'PNG')
            im.close()
        pathArr.append(file_path.replace("\\", "/"))
        file_page = file_page + 1
    return pathArr


def make(request):
    image_id = request.POST.get("image_id")
    content = request.POST.get("content")
    font_id = request.POST.get("font_id")
    fontSize = request.POST.get("fontSize")
    fontCount = request.POST.get("fontCount")
    fontColor = request.POST.get("fontColor")
    rowSpacing = request.POST.get("rowSpacing")
    start_x = request.POST.get("start_x")
    start_y = request.POST.get("start_y")
    line = request.POST.get("line")
    type = request.POST.get("type")
    if not image_id:
        return back_failed("参数错误")
    if not content:
        return back_failed("参数错误")
    if not font_id:
        return back_failed("参数错误")
    if not fontSize:
        return back_failed("参数错误")
    if not fontCount:
        return back_failed("参数错误")
    if not fontColor:
        return back_failed("参数错误")
    if not rowSpacing:
        return back_failed("参数错误")
    if not start_x:
        return back_failed("参数错误")
    if not start_y:
        return back_failed("参数错误")
    if not line:
        return back_failed("参数错误")
    if not type:
        return back_failed("参数错误")
    res = verify_token(request)
    if res == False:
        return back_failed("登录状态失效，请重新登录")
    else:
        email = res["email"]
        print(email)
        image = File.objects.get(id=image_id)
        font = File.objects.get(id=font_id)
        paths = draw(
            content=content,
            fontCount=int(fontCount),
            bg_path=image.path,
            font_path=font.path,
            x=int(start_x),
            y=int(start_y),
            spacing=float(rowSpacing),
            font_color=fontColor,
            line=int(line),
            temPath=email,
            fontSize=int(fontSize)
        )
        if type == "preview":
            return back_success(json.dumps(paths))
        else:
            title = request.POST.get("title")
            if not title:
                return back_failed("参数错误")
            folder = "assets" + os.sep + "master" + os.sep + str(email) + os.sep
            if not os.path.exists(folder):
                os.makedirs(folder)
            master_path = []
            for p in paths:
                des = folder + os.path.basename(p)
                shutil.move(p, str(des))
                master_path.append(str(des).replace("\\", "/"))
            Master.objects.create(
                email=email,
                path=json.dumps(master_path),
                title=title
            )
            return back_success(json.dumps(master_path))

def get(request):
    is_my_works = request.POST.get("is_my_works")
    if str(is_my_works)=="true":
        res = verify_token(request)
        if not res:
            return back_failed("登录状态失效，请重新登录")
        else:
            master = Master.objects.filter(email=res["email"])
    else:
        master = Master.objects.filter(visible=True)
    j = []
    for m in master:
        u = User.objects.get(email=m.email)
        j.append({
            "path": m.path,
            "title": m.title,
            "email": m.email,
            "id": m.id,
            "visible": m.visible,
            "nickname": u.nickname
        })
    print(j)
    return back_success(j)

def delete(request):
    res = verify_token(request)
    if res == False:
        return back_failed("登录状态失效，请重新登录")
    else:
        try:
            email = res["email"]
            work_id = request.POST.get("id")
            if not email:
                return back_failed("参数错误")
            if not work_id:
                return back_failed("参数错误")
            m = Master.objects.get(
                id=work_id,
                email=email
            )
            for p in json.loads(m.path):
                os.remove(p)  # 删除images,font
            m.delete()
            return back_success("删除成功")
        except Exception as e:
            return back_failed("API异常"+str(e))

def visible(request):
    res = verify_token(request)
    if res == False:
        return back_failed("登录状态失效，请重新登录")
    else:
        try:
            email = res["email"]
            id = request.POST.get("id")
            visible = request.POST.get("visible")
            if not email:
                return back_failed("参数错误")
            if not id:
                return back_failed("参数错误")
            if not visible:
                return back_failed("参数错误")

            v = False
            if visible == "0":
                v = True
            else:
                v = False
            m = Master.objects.filter(
                id=id,
                email=email,
            )
            if m.exists():
                m.update(visible=v)
                return back_success("更新成功")
            else:
                return back_success("更新失败")
        except Exception as e:
            return back_failed("API异常"+str(e))